package com.bsc.rtc.lib.libraries.RetrofitNet;

import android.util.Log;

import androidx.annotation.NonNull;

import com.bsc.rtc.lib.libraries.RetrofitNet.api.APIServiceCreator;
import com.bsc.rtc.lib.libraries.RetrofitNet.api.DownApiServiceCreator;
import com.bsc.rtc.lib.libraries.RetrofitNet.download.DownloadListener;
import com.bsc.rtc.lib.libraries.RetrofitNet.transport.FileRequestBody;
import com.bsc.rtc.lib.libraries.RetrofitNet.transport.FileResponseBody;
import com.bsc.rtc.lib.libraries.RetrofitNet.transport.RetrofitCallback;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FileNetWorkUtils {
    String TAG = "fileUpDown";

    public FileNetWorkUtils() {

    }

    public String upload(String filePath) {
        RetrofitCallback<String> callback = new RetrofitCallback<String>() {
            @Override
            public void onSuccess(Call<String> call, Response<String> response) {
                Log.e(TAG, "onSuccess");
                //进度更新结束
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.e(TAG, "onFailure " + t.getLocalizedMessage());
                //进度更新结束
            }

            @Override
            public void onLoading(long total, long progress) {
                super.onLoading(total, progress);
                //此处进行进度更新
                Log.i(TAG, "total=" + total + " progress" + progress);
            }
        };
        File file = new File(filePath);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        //通过该行代码将RequestBody转换成特定的FileRequestBody
        // FileRequestBody body1 = new FileRequestBody(body, callback);

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body);
        Call<String> call = new APIServiceCreator().getRequester().uploadFile(part);
        call.enqueue(callback);
        return null;
    }

    public static void download(String url, final String path, final DownloadListener downloadListener) {

        Call<ResponseBody> call = new APIServiceCreator().getRequester().download(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                //将Response写入到从磁盘中，详见下面分析
                //注意，这个方法是运行在子线程中的
                writeResponseToDisk(path, response, downloadListener);
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
                downloadListener.onFail("网络错误～");
            }
        });
    }
    private static void writeResponseToDisk(String path, Response<ResponseBody> response, DownloadListener downloadListener) {
        //从response获取输入流以及总大小
        writeFileFromIS(new File(path), response.body().byteStream(), response.body().contentLength(), downloadListener);
    }

    private static int sBufferSize = 8192;

    //将输入流写入文件
    private static void writeFileFromIS(File file, InputStream is, long totalLength, DownloadListener downloadListener) {
        //开始下载
        downloadListener.onStart();

        //创建文件
        if (!file.exists()) {
            if (!file.getParentFile().exists())
                file.getParentFile().mkdir();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                downloadListener.onFail("createNewFile IOException");
            }
        }

        OutputStream os = null;
        long currentLength = 0;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            byte data[] = new byte[sBufferSize];
            int len;
            while ((len = is.read(data, 0, sBufferSize)) != -1) {
                os.write(data, 0, len);
                currentLength += len;
                //计算当前下载进度
                downloadListener.onProgress((int) (100 * currentLength / totalLength));
            }
            //下载完成，并返回保存的文件路径
            downloadListener.onFinish(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            downloadListener.onFail("IOException");
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
